<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="订单名称">
              <a-input placeholder="请输入订单名称" v-model="queryParam.orderName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="订单类型">
              <a-select placeholder="请选择订单类型" v-model="queryParam.orderType" allowClear>
                <a-select-option v-for="(value, key) in dictCache.orderType" :key="key" :value="key">
                  {{ value }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="订单进度">
              <a-select placeholder="请选择订单进度" v-model="queryParam.orderProgress" allowClear>
                <a-select-option v-for="(value, key) in dictCache.orderProgress" :key="key" :value="key">
                  {{ value }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="8">
              <a-form-item label="下单日期">
                <j-date placeholder="请选择下单日期" v-model="queryParam.orderDate"></j-date>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="程序员">
                <a-input placeholder="请输入程序员姓名" v-model="queryParam.programmerName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="客户微信">
                <a-input placeholder="请输入客户微信" v-model="queryParam.customerWechat"></a-input>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('订单信息')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"
                @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>
    
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
        style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        <template v-if="selectedRowKeys.length > 0">
          <span style="margin-left: 24px">
            总利润: <a style="font-weight: 600">{{ getSelectedTotalProfit() }}</a> 元
          </span>
        </template>
      </div>
      
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
        :scroll="{ x: 1500, y: 600 }">
        
        <template slot="orderTypeSlot" slot-scope="text">
          <a-tag :color="getOrderTypeColor(text)">
            {{ getOrderTypeText(text) }}
          </a-tag>
        </template>
        <template slot="orderProgressSlot" slot-scope="text">
          <a-tag :color="getOrderProgressColor(text)">
            {{ getOrderProgressText(text) }}
          </a-tag>
        </template>
        <template slot="programmerNameSlot" slot-scope="text, record">
          <span>{{ getProgrammerName(record) }}</span>
        </template>
        <span slot="action" slot-scope="text, record">
          <div class="action-buttons">
            <a-tooltip title="编辑">
              <a-button type="primary" shape="circle" icon="edit" size="small" @click="handleEdit(record)"></a-button>
            </a-tooltip>
            <a-tooltip title="结算">
              <a-button type="primary" shape="circle" icon="dollar" size="small" @click="handleBill(record)"></a-button>
            </a-tooltip>
            <a-tooltip title="结算记录">
              <a-button type="primary" shape="circle" icon="file-text" size="small"
                        @click="handleViewBills(record)"></a-button>
            </a-tooltip>
            <a-dropdown :trigger="['click']">
              <a-tooltip title="更多操作">
                <a-button type="primary" shape="circle" icon="ellipsis" size="small"></a-button>
              </a-tooltip>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a-button type="link" icon="delete" style="color: #ff4d4f;">删除</a-button>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item>
                  <a-button type="link" icon="printer" @click="handlePrint(record)">打印</a-button>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->
    
    <!-- 表单区域 -->
    <bOrderInfo-modal ref="modalForm" @ok="modalFormOk"></bOrderInfo-modal>
    
    <!-- 结算模态框 -->
    <b-programmer-bill-modal ref="billModalForm" @ok="billModalFormOk"></b-programmer-bill-modal>
    
    <!-- 结算记录模态框 -->
    <b-programmer-bill-list-modal ref="billListModalForm"></b-programmer-bill-list-modal>
  </a-card>
</template>

<script>
import BOrderInfoModal from './modules/BOrderInfoModal'
import BProgrammerBillModal from './modules/BProgrammerBillModal'
import BProgrammerBillListModal from './modules/BProgrammerBillListModal'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JDate from '@/components/jeecg/JDate'
import {getAction} from '@/api/manage'

export default {
  name: "BOrderInfoList",
  mixins: [JeecgListMixin],
  components: {
    BOrderInfoModal,
    BProgrammerBillModal,
    BProgrammerBillListModal,
    JDictSelectTag,
    JDate
  },
  data() {
    return {
      description: '订单信息管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          fixed: 'left',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '订单名称',
          align: "center",
          dataIndex: 'orderName',
          width: 180,
          ellipsis: true
        },
        {
          title: '订单金额',
          align: "center",
          dataIndex: 'orderAmount',
          width: 100
        },
        {
          title: '订单类型',
          align: "center",
          dataIndex: 'orderType',
          width: 100,
          scopedSlots: {customRender: 'orderTypeSlot'}
        },
        {
          title: '下单日期',
          align: "center",
          dataIndex: 'orderDate',
          width: 110
        },
        {
          title: '交付日期',
          align: "center",
          dataIndex: 'deliveryDate',
          width: 110
        },
        
        {
          title: '程序员',
          align: "center",
          dataIndex: 'programmerId',
          width: 100,
          scopedSlots: {customRender: 'programmerNameSlot'}
        },
        {
          title: '抽成比例',
          align: "center",
          dataIndex: 'commissionRate',
          width: 90,
          customRender: (text) => {
            return text ? text + '%' : '';
          }
        },
        
        {
          title: '程序员分成金额',
          align: "center",
          dataIndex: 'programmerAmount',
          width: 120
        },
        {
          title: '本单利润',
          align: "center",
          dataIndex: 'profit',
          width: 100
        },
        {
          title: '订单进度',
          align: "center",
          dataIndex: 'orderProgress',
          width: 100,
          scopedSlots: {customRender: 'orderProgressSlot'}
        },
        {
          title: '售后截止日期',
          align: "center",
          dataIndex: 'afterSaleEndDate',
          width: 120
        },
        
        {
          title: '客户名称',
          align: "center",
          dataIndex: 'customerName',
          width: 100,
          ellipsis: true
        },
        {
          title: '客户微信',
          align: "center",
          dataIndex: 'customerWechat',
          width: 100,
          ellipsis: true
        },
        
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          fixed: 'right',
          scopedSlots: {customRender: 'action'},
          width: 200
        }
      ],
      url: {
        list: "/order/bOrderInfo/list",
        delete: "/order/bOrderInfo/delete",
        deleteBatch: "/order/bOrderInfo/deleteBatch",
        exportXlsUrl: "/order/bOrderInfo/exportXls",
        importExcelUrl: "/order/bOrderInfo/importExcel",
        getProgrammerById: "/order/bProgrammerInfo/queryById"
      },
      dictOptions: {},
      superFieldList: [],
      programmerCache: {},
      // 字典缓存
      dictCache: {
        orderType: {},
        orderProgress: {}
      },
      // 自定义分页配置
      ipagination: {
        current: 1,
        pageSize: 50,
        pageSizeOptions: ['50', '100', '200', '500'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    }
  },
  created() {
    this.getSuperFieldList();
    // 初始化字典数据
    this.initDictData();
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  methods: {
    initDictConfig() {
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({type: 'string', value: 'orderName', text: '订单名称', dictCode: ''})
      fieldList.push({type: 'string', value: 'orderType', text: '订单类型', dictCode: 'order_type'})
      fieldList.push({type: 'Date', value: 'orderDate', text: '下单日期'})
      fieldList.push({type: 'Date', value: 'deliveryDate', text: '交付日期'})
      fieldList.push({type: 'Date', value: 'afterSaleEndDate', text: '售后截止日期'})
      fieldList.push({type: 'double', value: 'orderAmount', text: '订单金额', dictCode: ''})
      fieldList.push({type: 'double', value: 'commissionRate', text: '抽成比例', dictCode: ''})
      fieldList.push({type: 'double', value: 'programmerAmount', text: '程序员分成金额', dictCode: ''})
      fieldList.push({type: 'double', value: 'profit', text: '本单利润', dictCode: ''})
      fieldList.push({type: 'string', value: 'orderProgress', text: '订单进度', dictCode: 'order_progress'})
      fieldList.push({type: 'string', value: 'programmerId', text: '程序员id', dictCode: ''})
      fieldList.push({type: 'string', value: 'customerName', text: '客户名称', dictCode: ''})
      fieldList.push({type: 'string', value: 'customerWechat', text: '客户微信', dictCode: ''})
      fieldList.push({type: 'string', value: 'orderRemark', text: '订单备注', dictCode: ''})
      this.superFieldList = fieldList
    },
    // 获取程序员名称
    getProgrammerName(record) {
      if (!record.programmerId) {
        return '';
      }
      
      // 如果缓存中有，直接返回
      if (this.programmerCache[record.programmerId]) {
        return this.programmerCache[record.programmerId];
      }
      
      // 否则从服务器获取
      getAction(this.url.getProgrammerById, {id: record.programmerId}).then(res => {
        if (res.success) {
          this.programmerCache[record.programmerId] = res.result.realName;
          // 强制更新视图
          this.$forceUpdate();
        }
      });
      
      return '加载中...';
    },
    
    // 处理结算按钮点击
    handleBill(record) {
      // 确保有程序员信息
      if (!record.programmerId) {
        this.$message.warning('该订单未分配程序员，无法进行结算');
        return;
      }
      
      // 获取程序员名称
      const programmerName = this.programmerCache[record.programmerId] || '加载中...';
      
      // 打开结算模态框
      this.$refs.billModalForm.show({
        ...record,
        programmerName: programmerName
      });
    },
    
    // 结算模态框确认回调
    billModalFormOk() {
      // 刷新列表
      this.loadData();
      // 显示成功消息
      this.$message.success('结算信息保存成功');
    },
    
    // 查看结算记录
    handleViewBills(record) {
      // 确保有程序员信息
      if (!record.programmerId) {
        this.$message.warning('该订单未分配程序员，无法查看结算记录');
        return;
      }
      
      // 获取程序员详细信息
      getAction(this.url.getProgrammerById, {id: record.programmerId}).then(res => {
        if (res.success) {
          // 更新缓存
          this.programmerCache[record.programmerId] = res.result.realName;
          
          // 打开结算记录模态框
          this.$refs.billListModalForm.show({
            ...record,
            programmerName: res.result.realName,
            phone: res.result.phone || ''
          });
        } else {
          // 如果获取失败，仍然打开模态框，但不显示电话
          const programmerName = this.programmerCache[record.programmerId] || '加载中...';
          this.$refs.billListModalForm.show({
            ...record,
            programmerName: programmerName,
            phone: ''
          });
        }
      });
    },
    // 初始化字典数据
    initDictData() {
      // 初始化订单类型字典
      this.initDict('order_type', 'orderType');
      // 初始化订单进度字典
      this.initDict('order_progress', 'orderProgress');
    },
    // 初始化指定字典
    initDict(dictCode, dictType) {
      getAction('/sys/dict/getDictItems/' + dictCode).then(res => {
        if (res.success) {
          const dict = {};
          res.result.forEach(item => {
            dict[item.value] = item.text;
          });
          this.$set(this.dictCache, dictType, dict);
          console.log(`字典[${dictType}]加载完成:`, dict);
        }
      });
    },
    // 获取订单类型文本
    getOrderTypeText(type) {
      if (!type) return '';
      return this.dictCache.orderType[type] || type;
    },
    // 获取订单进度文本
    getOrderProgressText(progress) {
      if (!progress) return '';
      return this.dictCache.orderProgress[progress] || progress;
    },
    // 获取订单类型颜色
    getOrderTypeColor(type) {
      // 根据订单类型设置不同的颜色
      switch (type) {
        case '1':
          return 'blue';       // 毕设全包
        case '2':
          return 'purple';     // 单程序
        case '3':
          return 'cyan';       // 单论文
        case '4':
          return 'geekblue';   // 二开
        case '5':
          return 'green';      // 项目部署
        default:
          return 'default';
      }
    },
    // 获取订单进度颜色
    getOrderProgressColor(progress) {
      // 根据订单进度设置不同的颜色
      switch (progress) {
        case '01':
          return 'blue';      // 首款已支付
        case '02':
          return 'cyan';      // 首款已到账
        case '03':
          return 'purple';    // 尾款已支付
        case '04':
          return 'geekblue';  // 尾款已到账
        case '05':
          return 'orange';    // 售后中
        case '06':
          return 'green';     // 完成
        default:
          return 'default';
      }
    },
    
    // 打印订单
    handlePrint(record) {
      this.$message.info('订单打印功能即将上线');
    },
    
    // 计算选中订单的总利润
    getSelectedTotalProfit() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length === 0) {
        return '0.00';
      }
      
      // 找出选中的行数据
      const selectedRows = this.dataSource.filter(item => this.selectedRowKeys.includes(item.id));
      
      // 计算总利润
      let totalProfit = 0;
      selectedRows.forEach(row => {
        totalProfit += Number(row.profit || 0);
      });
      
      // 返回格式化后的总利润
      return totalProfit.toFixed(2);
    }
  }
}
</script>
<style>
@import '~@assets/less/common.less';

/* 标签样式优化 */
.ant-tag {
  margin-right: 0;
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

/* 圆形按钮样式 */
.action-buttons .ant-btn-circle {
  width: 28px;
  height: 28px;
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.action-buttons .ant-btn-circle:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 下拉菜单样式 */
.ant-dropdown-menu {
  padding: 4px 0;
  border-radius: 4px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
}

.ant-dropdown-menu-item {
  padding: 8px 16px;
  transition: background-color 0.3s;
}

.ant-dropdown-menu-item:hover {
  background-color: #f5f5f5;
}

.ant-dropdown-menu-item .ant-btn-link {
  padding: 0;
  height: auto;
  font-size: 14px;
}

/* 表格内容垂直居中 */
.ant-table-row td {
  vertical-align: middle !important;
}
</style> 